//! 示例数据填充模块
//! 提供预定义的测试数据和数据初始化功能

use crate::models::party::*;
use crate::services::*;
use crate::Result;

/// 示例数据生成器
pub struct SampleDataGenerator {
    party_service: PartyService,
    organization_service: OrganizationService,
    contact_service: ContactService,
    customer_service: CustomerService,
}

impl SampleDataGenerator {
    /// 创建新的示例数据生成器
    pub fn new(
        party_service: PartyService,
        organization_service: OrganizationService,
        contact_service: ContactService,
        customer_service: CustomerService,
    ) -> Self {
        Self {
            party_service,
            organization_service,
            contact_service,
            customer_service,
        }
    }

    /// 生成所有示例数据
    pub async fn generate_all_sample_data(&mut self) -> Result<()> {
        println!("开始生成示例数据...");
        
        // 1. 创建示例组织
        self.create_sample_organizations().await?;
        
        // 2. 创建示例个人
        self.create_sample_persons().await?;
        
        // 3. 创建组织关系
        self.create_organization_relationships().await?;
        
        // 4. 添加组织成员
        self.add_organization_members().await?;
        
        // 5. 创建联系方式
        self.create_contact_mechanisms().await?;
        
        println!("示例数据生成完成！");
        Ok(())
    }

    /// 创建示例组织
    async fn create_sample_organizations(&mut self) -> Result<()> {
        println!("创建示例组织...");
        
        let organizations = vec![
            PartyGroup {
                party_id: "ORG_ACME_CORP".to_string(),
                group_name: Some("ACME Corporation".to_string()),
                group_name_local: None,
                office_site_name: Some("总部".to_string()),
                annual_revenue: Some(10000000.0),
                num_employees: Some(500),
                ticker_symbol: Some("ACME".to_string()),
                comments: Some("示例公司 - ACME Corporation".to_string()),
                logo_image_url: None,
            },
            PartyGroup {
                party_id: "ORG_TECH_DEPT".to_string(),
                group_name: Some("技术部".to_string()),
                group_name_local: None,
                office_site_name: Some("研发中心".to_string()),
                annual_revenue: None,
                num_employees: Some(50),
                ticker_symbol: None,
                comments: Some("ACME公司技术部门".to_string()),
                logo_image_url: None,
            },
            PartyGroup {
                party_id: "ORG_SALES_DEPT".to_string(),
                group_name: Some("销售部".to_string()),
                group_name_local: None,
                office_site_name: Some("销售中心".to_string()),
                annual_revenue: None,
                num_employees: Some(30),
                ticker_symbol: None,
                comments: Some("ACME公司销售部门".to_string()),
                logo_image_url: None,
            },
        ];

        for org in organizations {
            match self.party_service.create_party_group(&org).await {
                Ok(party_id) => println!("创建组织成功: {} ({})", org.group_name.as_deref().unwrap_or("未知"), party_id),
                Err(e) => println!("创建组织失败: {} - {}", org.group_name.as_deref().unwrap_or("未知"), e),
            }
        }

        Ok(())
    }

    /// 创建示例个人
    async fn create_sample_persons(&mut self) -> Result<()> {
        println!("创建示例个人...");
        
        let persons = vec![
            Person {
                party_id: "PERSON_JOHN_DOE".to_string(),
                salutation: Some("Mr.".to_string()),
                first_name: Some("John".to_string()),
                middle_name: None,
                last_name: Some("Doe".to_string()),
                personal_title: Some("软件工程师".to_string()),
                suffix: None,
                nickname: Some("Johnny".to_string()),
                first_name_local: None,
                middle_name_local: None,
                last_name_local: None,
                other_local: None,
                member_id: None,
                gender: Some("M".to_string()),
                birth_date: None,
                deceased_date: None,
                height: None,
                weight: None,
                mothers_maiden_name: None,

                marital_status_enum_id: Some("MARRIED".to_string()),
                social_security_number: None,
                passport_number: None,
                passport_expire_date: None,
                total_years_work_experience: Some(5.0),
                comments: Some("资深软件工程师".to_string()),
                employment_status_enum_id: Some("EMPLOYED".to_string()),
                residence_status_enum_id: Some("RESIDENT".to_string()),
                occupation: Some("软件开发".to_string()),
                years_with_employer: Some(3),
                months_with_employer: Some(6),
                existing_customer: Some(false),
                card_id: None,
            },
            Person {
                party_id: "PERSON_JANE_SMITH".to_string(),
                salutation: Some("Ms.".to_string()),
                first_name: Some("Jane".to_string()),
                middle_name: None,
                last_name: Some("Smith".to_string()),
                personal_title: Some("产品经理".to_string()),
                suffix: None,
                nickname: Some("Janie".to_string()),
                first_name_local: None,
                middle_name_local: None,
                last_name_local: None,
                other_local: None,
                member_id: None,
                gender: Some("F".to_string()),
                birth_date: None,
                deceased_date: None,
                height: None,
                weight: None,
                mothers_maiden_name: None,

                marital_status_enum_id: Some("SINGLE".to_string()),
                social_security_number: None,
                passport_number: None,
                passport_expire_date: None,
                total_years_work_experience: Some(7.0),
                comments: Some("经验丰富的产品经理".to_string()),
                employment_status_enum_id: Some("EMPLOYED".to_string()),
                residence_status_enum_id: Some("RESIDENT".to_string()),
                occupation: Some("产品管理".to_string()),
                years_with_employer: Some(2),
                months_with_employer: Some(3),
                existing_customer: Some(false),
                card_id: None,
            },
            Person {
                party_id: "PERSON_BOB_WILSON".to_string(),
                salutation: Some("Mr.".to_string()),
                first_name: Some("Bob".to_string()),
                middle_name: None,
                last_name: Some("Wilson".to_string()),
                personal_title: Some("销售经理".to_string()),
                suffix: None,
                nickname: Some("Bobby".to_string()),
                first_name_local: None,
                middle_name_local: None,
                last_name_local: None,
                other_local: None,
                member_id: None,
                gender: Some("M".to_string()),
                birth_date: None,
                deceased_date: None,
                height: None,
                weight: None,
                mothers_maiden_name: None,

                marital_status_enum_id: Some("MARRIED".to_string()),
                social_security_number: None,
                passport_number: None,
                passport_expire_date: None,
                total_years_work_experience: Some(10.0),
                comments: Some("资深销售经理".to_string()),
                employment_status_enum_id: Some("EMPLOYED".to_string()),
                residence_status_enum_id: Some("RESIDENT".to_string()),
                occupation: Some("销售管理".to_string()),
                years_with_employer: Some(5),
                months_with_employer: Some(0),
                existing_customer: Some(false),
                card_id: None,
            },
        ];

        for person in persons {
            match self.party_service.create_person(&person).await {
                Ok(party_id) => {
                    let name = format!("{} {}", 
                        person.first_name.as_deref().unwrap_or(""),
                        person.last_name.as_deref().unwrap_or(""));
                    println!("创建个人成功: {} ({})", name.trim(), party_id);
                },
                Err(e) => {
                    let name = format!("{} {}", 
                        person.first_name.as_deref().unwrap_or(""),
                        person.last_name.as_deref().unwrap_or(""));
                    println!("创建个人失败: {} - {}", name.trim(), e);
                },
            }
        }

        Ok(())
    }

    /// 创建组织关系
    async fn create_organization_relationships(&mut self) -> Result<()> {
        println!("创建组织关系...");
        
        // 技术部是ACME公司的子部门
        match self.organization_service.create_organization_relationship(
            "ORG_TECH_DEPT",
            "ORG_ACME_CORP"
        ).await {
            Ok(_) => println!("创建组织关系成功: 技术部 -> ACME Corporation"),
            Err(e) => println!("创建组织关系失败: 技术部 -> ACME Corporation - {}", e),
        }
        
        // 销售部是ACME公司的子部门
        match self.organization_service.create_organization_relationship(
            "ORG_SALES_DEPT",
            "ORG_ACME_CORP"
        ).await {
            Ok(_) => println!("创建组织关系成功: 销售部 -> ACME Corporation"),
            Err(e) => println!("创建组织关系失败: 销售部 -> ACME Corporation - {}", e),
        }

        Ok(())
    }

    /// 添加组织成员
    async fn add_organization_members(&mut self) -> Result<()> {
        println!("添加组织成员...");
        
        // John Doe 加入技术部
        match self.organization_service.add_member(
            "ORG_TECH_DEPT",
            "PERSON_JOHN_DOE",
            "EMPLOYEE",
            Some("高级软件工程师"),
            None
        ).await {
            Ok(_) => println!("添加成员成功: John Doe -> 技术部"),
            Err(e) => println!("添加成员失败: John Doe -> 技术部 - {}", e),
        }
        
        // Jane Smith 加入技术部
        match self.organization_service.add_member(
            "ORG_TECH_DEPT",
            "PERSON_JANE_SMITH",
            "MANAGER",
            Some("产品经理"),
            None
        ).await {
            Ok(_) => println!("添加成员成功: Jane Smith -> 技术部"),
            Err(e) => println!("添加成员失败: Jane Smith -> 技术部 - {}", e),
        }
        
        // Bob Wilson 加入销售部
        match self.organization_service.add_member(
            "ORG_SALES_DEPT",
            "PERSON_BOB_WILSON",
            "MANAGER",
            Some("销售经理"),
            None
        ).await {
            Ok(_) => println!("添加成员成功: Bob Wilson -> 销售部"),
            Err(e) => println!("添加成员失败: Bob Wilson -> 销售部 - {}", e),
        }

        Ok(())
    }

    /// 创建联系方式
    async fn create_contact_mechanisms(&mut self) -> Result<()> {
        println!("创建联系方式...");
        
        // John Doe 的联系方式
        match self.contact_service.add_email_address("PERSON_JOHN_DOE", "john.doe@acme.com", "PRIMARY_EMAIL", true).await {
            Ok(_) => println!("创建联系方式成功: john.doe@acme.com"),
            Err(e) => println!("创建联系方式失败: john.doe@acme.com - {}", e),
        }
        
        // Jane Smith 的联系方式
        match self.contact_service.add_email_address("PERSON_JANE_SMITH", "jane.smith@acme.com", "PRIMARY_EMAIL", true).await {
            Ok(_) => println!("创建联系方式成功: jane.smith@acme.com"),
            Err(e) => println!("创建联系方式失败: jane.smith@acme.com - {}", e),
        }
        
        // Bob Wilson 的联系方式
        match self.contact_service.add_email_address("PERSON_BOB_WILSON", "bob.wilson@acme.com", "PRIMARY_EMAIL", true).await {
            Ok(_) => println!("创建联系方式成功: bob.wilson@acme.com"),
            Err(e) => println!("创建联系方式失败: bob.wilson@acme.com - {}", e),
        }
        
        // ACME Corp 的联系方式
        match self.contact_service.add_email_address("ORG_ACME_CORP", "info@acme.com", "PRIMARY_EMAIL", true).await {
            Ok(_) => println!("创建联系方式成功: info@acme.com"),
            Err(e) => println!("创建联系方式失败: info@acme.com - {}", e),
        }

        Ok(())
    }

    /// 清理所有示例数据
    pub async fn cleanup_sample_data(&mut self) -> Result<()> {
        println!("清理示例数据...");
        
        // 注意：这里只是示例，实际实现需要根据具体的删除API来实现
        // 由于我们的服务目前没有实现删除功能，这里只是占位符
        
        println!("示例数据清理完成！");
        Ok(())
    }
}

/// 快速初始化示例数据的便捷函数
pub async fn init_sample_data(
    party_service: PartyService,
    organization_service: OrganizationService,
    contact_service: ContactService,
    customer_service: CustomerService,
) -> Result<()> {
    let mut generator = SampleDataGenerator::new(
        party_service,
        organization_service,
        contact_service,
        customer_service,
    );
    
    generator.generate_all_sample_data().await
}